// common_script.js

// 预定义的颜色集合
const colorPalette = ['#FFFACD', '#FFF0F5', '#b4fde5', '#F0FFFF', '#f2e8f2', '#FFE4C4', '#ededed', '#eeeadb',
    '#e6d4c2', '#c2d2b5', '#e0e5df', '#d8caaf', '#c8d5d4', '#d5dfec'];

// 随机选择颜色
const getRandomColor = () => {
    return colorPalette[Math.floor(Math.random() * colorPalette.length)];
};

function toggleNodeExpansion(network, nodeId, nodes, edges) {
    const node = nodes.get(nodeId);
    if (node.expanded) {
        // 折叠：隐藏所有子节点及其子节点
        const allChildNodes = getAllChildNodes(nodeId, nodes);
        nodes.update(allChildNodes.map((n) => ({ id: n.id, hidden: true })));
        node.expanded = false;
    } else {
        // 展开：只显示下一层的子节点
        const directChildNodes = nodes.get({
            filter: (n) => n.parentId === nodeId,
        });
        nodes.update(directChildNodes.map((n) => ({ id: n.id, hidden: false })));
        node.expanded = true;
    }
    // 添加动态效果
    network.fit({ animation: { duration: 500, easingFunction: 'easeInOutQuad' } });
}

function getAllChildNodes(nodeId, nodes) {
    const childNodes = nodes.get({
        filter: (n) => n.parentId === nodeId,
    });
    let allChildNodes = [...childNodes];
    childNodes.forEach((child) => {
        allChildNodes = allChildNodes.concat(getAllChildNodes(child.id, nodes));
    });
    return allChildNodes;
}


const initGraph = (containerId, nodes, edges) => {

    const network = new vis.Network(
        document.getElementById(containerId),
        { nodes, edges },
        // commonOptions
        {
            nodes: {
                shape: 'dot',
                size: 25,
                font: { size: 14 }
            },
            edges: {
                smooth: false, // { type: 'dynamic' },
                width: 2
            },
            physics: {
                enabled: true // 禁用物理引擎，防止拖动后返回起点
            },
            layout: {
                improvedLayout: true // 启用改进的布局算法
            },
            interaction: {
                dragNodes: true // 允许拖动节点
            }
        }
    );

    network.fit(); // 初始居中
    network.moveTo({ position: { x: 0, y: 0 }, scale: 1 }); // 确保初始位置居中

    // 监听节点点击事件
    network.on("click", (event) => {
        if (event.nodes.length > 0) {
            const nodeId = event.nodes[0];
            toggleNodeExpansion(network, nodeId, nodes, edges);
        }
    });

    return network;
};

